/* syscalls.c */
#include <stdio.h>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdarg.h>

#include "bsp_config.h"

#undef errno
extern int errno;
extern int  _end;

int __io_getchar(void)
{
    while (LPUART_HAL_FLAG_RX_FULL_MASK != (LPUART_HAL_FLAG_RX_FULL_MASK & LPUART_HAL_GetStatus(BSP_LPUART_DEBUG_PORT)))
    {}
    return (int)LPUART_HAL_GetRxData(BSP_LPUART_DEBUG_PORT);
}

int __io_putchar(int ch)
{
    while (LPUART_HAL_FLAG_TX_EMPTY_MASK != (LPUART_HAL_FLAG_TX_EMPTY_MASK & LPUART_HAL_GetStatus(BSP_LPUART_DEBUG_PORT)))
    {}
    LPUART_HAL_SetTxData(BSP_LPUART_DEBUG_PORT, (unsigned char)ch);

    return ch;
}

caddr_t _sbrk ( int incr )
{
  static unsigned char *heap = NULL;
  unsigned char *prev_heap;

  if (heap == NULL) {
    heap = (unsigned char *)&_end;
  }
  prev_heap = heap;

  heap += incr;

  return (caddr_t) prev_heap;
}

int link(char *old, char *new)
{
    return -1;
}

int _close(int file)
{
    return -1;
}

int _fstat(int file, struct stat *st)
{
  st->st_mode = S_IFCHR;
  return 0;
}

int _isatty(int file)
{
  return 1;
}

int _lseek(int file, int ptr, int dir)
{
  return 0;
}

int _read(int file, char *ptr, int len)
{
    /* return 0; */
    //int rxCount;

    (void) file;

#if 0
    for (rxCount = 0U; rxCount < len; rxCount++)
    {
        ptr[rxCount] = __io_getchar();
#if 0
        while (LPUART_HAL_FLAG_RX_FULL_MASK != (LPUART_HAL_FLAG_RX_FULL_MASK & LPUART_HAL_GetStatus(BSP_LPUART_DEBUG_PORT)))
        {}
        ptr[rxCount] = LPUART_HAL_GetRxData(BSP_LPUART_DEBUG_PORT);
#endif
    }
#endif
    ptr[0] = __io_getchar();
    return 1U;
}

int _write(int file, char *ptr, int len)
{
    int txCount;

    (void) file;

    for (txCount = 0; txCount < len; txCount++)
    {
        __io_putchar(ptr[txCount]);
#if 0
        while (LPUART_HAL_FLAG_TX_EMPTY_MASK != (LPUART_HAL_FLAG_TX_EMPTY_MASK & LPUART_HAL_GetStatus(BSP_LPUART_DEBUG_PORT)))
        {}
        LPUART_HAL_SetTxData(BSP_LPUART_DEBUG_PORT, ptr[txCount]);
#endif
    }

    return len;
}

void abort(void)
{
    /* Abort called */
    while(1);
}

/* EOF. */
